package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult login(LoginDto dto) {
        //判断是否是游客登录
        if (!StringUtils.hasLength(dto.getPhone()) || !StringUtils.hasLength(dto.getPassword())) {
            String token = AppJwtUtil.getToken(0L);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }

        //根据电话获取用户
        String phone = dto.getPhone();
        ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone).eq(ApUser::getStatus, 0));
        if (null == user) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //获取盐值并加密和数据库的密码比对
        String salt = user.getSalt();
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));
        if (password.equals(user.getPassword())) {
            //登录成功返回
            user.setSalt("");
            user.setPassword("");
            String token = AppJwtUtil.getToken(user.getId().longValue());
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", user);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
    }
}
